package com.example.controller;

import com.example.pojo.Emp;
import com.example.pojo.PasswordParam;
import com.example.pojo.Result;
import com.example.pojo.LoginInfo;
import com.example.service.EmpService;
import com.example.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


/**
 * 登录Controller
 */
@Slf4j
@RestController
public class LoginController {

    @Autowired
    private EmpService empService;

    /**
     * 登录
     * @param emp
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Emp emp) {
        log.info("登录操作：{}", emp);
        LoginInfo loginInfo = empService.login(emp);

        if (loginInfo != null) {
            //获取jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginInfo.getId());
            claims.put("username", loginInfo.getUsername());
            loginInfo.setToken(JwtUtils.generateJwt(claims));

            return Result.success(loginInfo);
        }

        return Result.error("用户名或密码错误");
    }

    /**
     * 修改密码
     */
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody PasswordParam passwordParam) {
        log.info("修改密码：{}", passwordParam);
        empService.updatePassword(passwordParam);

        return Result.success();
    }
}
